package com.jj.util;

import java.util.HashMap;
import java.util.Map;

public class ThreadLocalContext {

    private static ThreadLocal<Map<String, Object>> threadLocalMap =
            ThreadLocal.withInitial(() -> new HashMap<>());

    private static ThreadLocal<Map<String, Object>> threadLocalMap1 =
            new ThreadLocal<Map<String, Object>>() {
                @Override
                protected Map<String, Object> initialValue() {
                    return new HashMap<>();
                }
            };

    public static void initThreadLocalContext(Map targetMap) {
        if (null == targetMap) {
            threadLocalMap = ThreadLocal.withInitial(() -> new HashMap<>());
        } else {
            threadLocalMap = ThreadLocal.withInitial(() -> targetMap);
        }
    }

    private static Map<String, Object> getHashMap() {
        return threadLocalMap.get();
    }

    public static void put(String key, Object value) {
        getHashMap().put(key, value);
    }

    public static Object get(String key) {
        return getHashMap().get(key);
    }

    public static void clear() {
        threadLocalMap.remove();
    }


    private ThreadLocalContext() {
        // 单例
    }


}
